#include "CAnimation.h"
#include "CFrame.h"
#include "AnimInfo.h"
#include "SGD Wrappers\CSGD_TextureManager.h"
#include "CEventSystem.h"
#include "SGD Wrappers\SGD_Math.h"
#include "SGD Wrappers\CSGD_Direct3D.h"

CAnimation::CAnimation()
{
	m_pTM = CSGD_TextureManager::GetInstance();
	m_pEMs = CEventSystem::GetInstance();
	m_fTimeWaited = 0;
	m_bIsPlaying = true;
}

CAnimation::~CAnimation()
{
}

void CAnimation::Play()
{
	Reset();
	m_bIsPlaying = true;
}

void CAnimation::Pause()
{
	m_bIsPlaying = false;
}

void CAnimation::Resume()
{
	m_bIsPlaying = true;
}

void CAnimation::Update(AnimInfo* anim, float fElapsedTime)
{
	if(!m_bIsPlaying)
		return;

	anim->SetElapsedTime(anim->GetElapsedTime() + fElapsedTime * m_fSpeed);

	if(anim->GetElapsedTime() > m_Frames[anim->GetCurFrame()]->GetDuration())
	{
		if(!m_Frames[anim->GetCurFrame()]->GetEvent().empty())
			CEventSystem::GetInstance()->SendEvent(m_Frames[anim->GetCurFrame()]->GetEvent(), anim->GetOwner());
		anim->SetElapsedTime(anim->GetElapsedTime() - m_Frames[anim->GetCurFrame()]->GetDuration());
		anim->SetCurFrame(anim->GetCurFrame()+1);
		anim->SetFinished(false);
		if(anim->GetCurFrame() >= int(m_Frames.size()))
		{
			if(GetAnimationType() == LOOPING)
				anim->SetCurFrame(0);
			else
			{
				Reset();
				anim->SetCurFrame(m_Frames.size() - 1);
				anim->SetFinished(true);
			}
		}
	}
}

void CAnimation::Reset()
{
	m_nCurrFrame = 0;
	m_fTimeWaited = 0;
}

void CAnimation::Render(int& CurrFrame, int nPosX, int nPosY, float fScale, float fRotation, bool bIsFlipped, DWORD dwColor)
{
	RECT rFrame = m_Frames[CurrFrame]->GetImageRect();
	POINT ptAnchor = m_Frames[CurrFrame]->GetAnchorPoint();

	float fScaleX = fScale;
	if(fRotation != -SGD_PI/2)
	{
		if(bIsFlipped)
		{
			fScaleX *= -1;
			int width = rFrame.right - rFrame.left;
			nPosX += (int)(width * fScale);
			ptAnchor.x = width - ptAnchor.x;
		}
	}
	else
	{
		if(!bIsFlipped)
		{
			fScaleX *= -1;
			int width = rFrame.right - rFrame.left;
			nPosX += (int)(width * fScale);
			ptAnchor.x = width - ptAnchor.x;
		}
	}

	m_pTM->Draw(m_nImageID, (int)(nPosX - ptAnchor.x*fScale), (int)(nPosY - ptAnchor.y*fScale), fScaleX, 
		fScale, &rFrame, (float)ptAnchor.x, (float)ptAnchor.y, fRotation, dwColor);
}

void CAnimation::AddFrame(CFrame* frame)
{
	m_Frames.push_back(frame);
}

void CAnimation::RemoveFrame()
{
	m_Frames.pop_back();
}